<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace hiduoke\services\workWechat;

use app\common\model\wework\WeworkApps;
use EasyWeChat\Factory;
use Exception;

trait WorkWechatAppsService
{
    protected $AppsConfig = null;

    /**
     * @var \EasyWeChat\Work\Application
     */
    protected $AppsApp = null;

    /**
     * 获取自建应用配置
     * @return array
     */
    public function getAppsConfig($app_id = 0)
    {
        if ($this->AppsConfig) return $this->AppsConfig;
        if (!$app_id) {
            $app_id = getPlatformAddonConfig()['app_id'] ?? 0;
            if (!$app_id) {
                $app_id = (new WeworkApps())->where(['plaid' => get_plaid()])->where('is_default', 1)->value('id');
            }
        }
        $app = (new WeworkApps())->where(['id' => $app_id])->find();
        if (!$app) {
            throw new Exception("自建应用不存在,或者未指定", 10000);
        }
        $config = [
            'corp_id'  => $this->corp_id,
            'agent_id' => $app['agent_id'],
            'secret'   => $app['config']['secret'],
            'token'    => $app['config']['token'],
            'aes_key'  => $app['config']['aes_key'],
            'log'      => [
                'default'  => 'error', // 默认使用的 channel，生产环境可以改为下面的 prod
                'channels' => [
                    'error' => [
                        'driver' => 'single',
                        'path'   => '/tmp/easywechat/work_wechat_error.log',
                        'level'  => 'error',
                    ],
                ],
            ],
        ];
        return $config;
    }

    /**
     * 获取自建应用Application
     * @param $app_id int 自建应用ID
     * @param $config array 自建应用配置
     * @return \EasyWeChat\Work\Application|null
     * @throws Exception
     */
    public function getAppsApp($app_id = 0, $config = [])
    {
        if ($this->AppsApp) {
            return $this->AppsApp;
        }
        if (!$config) {
            $this->AppsConfig = $this->getAppsConfig($app_id);
        } else {
            $this->AppsConfig = $config;
        }
        $this->AppsApp = Factory::work($this->AppsConfig);
        return $this->AppsApp;
    }
}
